package com.tfswx.jkgl.designer.service.impl;

import com.alibaba.fastjson.JSON;
import com.tfswx.jkgl.designer.bean.JsonResult;
import com.tfswx.jkgl.designer.dto.fs.FileDownloadInputDTO;
import com.tfswx.jkgl.designer.service.FsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.ClientAbortException;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * @author Ricky
 * @date 2021/4/19
 */
@Slf4j
@Service
public class FsServiceImpl implements FsService {

    @Resource
    private HttpServletRequest request;
    @Resource
    private HttpServletResponse response;

    @Override
    public void download(FileDownloadInputDTO inputDto) {
        response.setCharacterEncoding("utf-8");
        try {

            String filePath = inputDto.getFilePath();
            String fileName = inputDto.getNewFileName();

            if (!StringUtils.hasText(filePath)) {
                throw new RuntimeException("filePath-不能为空");
            }

            File file = new File(filePath);
            if (!file.exists()) {
                throw new RuntimeException("文件未找到");
            }
            if (!StringUtils.hasText(fileName)) {
                fileName = file.getName();
            }
            download(file, fileName);
        } catch (Exception e) {
            response.setStatus(500);
            String s = JSON.toJSONString(JsonResult.failed(e.getMessage()));
            try {
                response.getWriter().write(s);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void download(File file, String fileName) {
        try (InputStream is = new FileInputStream(file)) {
            this.download(is, fileName);
        } catch (FileNotFoundException e) {
            throw new RuntimeException("文件未找到", e);
        } catch (IOException e) {
            throw new RuntimeException("IO异常", e);
        }
    }

    @Override
    public void download(File file) {
        download(file, file.getName());
    }

    @Override
    public void download(byte[] bytes, String fileName) {
        this.download(new ByteArrayInputStream(bytes), fileName);
    }

    @Override
    public void download(InputStream is, String fileName) {
        response.setCharacterEncoding("utf-8");
        // 设置强制下载不打开
        // response.setContentType("application/force-download");
        String fileNameHandled;
        try {
            String fileNameByEncode = URLEncoder.encode(fileName, "utf-8");
            fileNameHandled = fileNameByEncode.replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("文件名称转码失败", e);
        }
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileNameHandled);
        response.addHeader("fileName", fileNameHandled);
        response.addHeader("Access-Control-Expose-Headers", "fileName");
        response.addHeader("Accept-Ranges", "bytes");

        long fileLength = 0;
        try {
            if (is instanceof FileInputStream) {
                fileLength = is.available();
            }
        } catch (IOException e) {
            throw new RuntimeException("大小读取失败", e);
        }
        long pastLength = 0;// 记录已下载文件大小
        int rangeSwitch = 0;// 0：从头开始的全文下载；1：从某字节开始的下载（bytes=27000-）；2：从某字节开始到某字节结束的下载（bytes=27000-39000）
        long toLength;// 记录客户端需要下载的字节段的最后一个字节偏移量（比如bytes=27000-39000，则这个值是为39000）
        long contentLength;// 客户端请求的字节总量
        String rangeBytes;// 记录客户端传来的形如“bytes=27000-”或者“bytes=27000-39000”的内容
        int bsize = 1024;// 缓冲区大小
        byte[] b = new byte[bsize];// 暂存容器
        String range = request.getHeader("Range");
        if (range != null && range.trim().length() > 0 && !"null".equals(range)) {
            log.info("Range：" + range);
            rangeBytes = range.replaceAll("bytes=", "");
            if (rangeBytes.endsWith("-")) {
                rangeSwitch = 1;
                rangeBytes = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                pastLength = Long.parseLong(rangeBytes.trim());
                contentLength = fileLength - pastLength;
            } else {
                rangeSwitch = 2;
                String temp0 = rangeBytes.substring(0, rangeBytes.indexOf('-'));
                String temp2 = rangeBytes.substring(rangeBytes.indexOf('-') + 1);
                pastLength = Long.parseLong(temp0.trim());
                toLength = Long.parseLong(temp2);
                contentLength = toLength - pastLength + 1;// 客户端请求的是
                // 1275856879-1275877358
                // 之间的字节
            }
        } else {// 从开始进行下载
            contentLength = fileLength;// 客户端要求全文下载
        }
        /*
         * 如果设设置了Content-Length，则客户端会自动进行多线程下载。如果不希望支持多线程，则不要设置这个参数。 响应的格式是:
         * Content-Length: [文件的总大小] - [客户端请求的下载的文件块的开始字节]
         * ServletActionContext.getResponse().setHeader("Content-Length", new
         * Long(file.length() - p).toString());
         */
        // 如果是第一次下,还没有断点续传,状态是默认的 200,无需显式设置;响应的格式是:HTTP/1.1

        if (rangeSwitch != 0) {
            response.setStatus(206);
            // 不是从最开始下载，断点下载响应号为206
            // 响应的格式是:
            // Content-Range: bytes [文件块的开始字节]-[文件的总大小 - 1]/[文件的总大小]
            log.info("-- 片段下载，服务器即将开始断点续传...");
            switch (rangeSwitch) {
                case 1: {// 针对 bytes=27000- 的请求
                    String contentRange = "bytes " + pastLength + "-" + (fileLength - 1) + "/" + fileLength;
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                case 2: {// 针对 bytes=27000-39000 的请求
                    String contentRange = range.replace("=", " ") + "/" + fileLength;
                    response.setHeader("Content-Range", contentRange);
                    break;
                }
                default: {
                    break;
                }
            }
        } else {
            String contentRange = "bytes " + "0-" + (fileLength - 1) + "/" + fileLength;
            response.setHeader("Content-Range", contentRange);
            // 是从开始下载
            log.info("-- 是从开始到最后完整下载！");
        }

        if (is instanceof FileInputStream) {
            response.setHeader("Content-Length", String.valueOf(fileLength));
        }
        try (OutputStream out = new BufferedOutputStream(response.getOutputStream())) {

            try {
                // is.skip(pastLength);
            } catch (Exception e) {
                // ignore
            }
            long outLength = 0;// 实际输出字节数
            switch (rangeSwitch) {
                case 0: {
                }
                case 1: {
                    outLength = IOUtils.copy(is, out, 1024);
                    break;
                }
                case 2: {
                    int n;
                    long readLength = 0;// 记录已读字节数
                    while (readLength <= contentLength - pastLength) {// 大部分字节在这里读取
                        n = is.read(b);
                        readLength += n;
                        out.write(b, 0, n);
                        outLength += n;
                    }
                    if (readLength <= contentLength) {// 余下的不足 1024 个字节在这里读取
                        n = is.read(b, 0, (int) (contentLength - readLength));
                        out.write(b, 0, n);
                        outLength += n;
                    }
                    break;
                }
                default: {
                    break;
                }
            }
            log.info("Content-Length为：" + contentLength + "；实际输出字节数：" + outLength);
            out.flush();

        } catch (ClientAbortException e) {
            /*
             * 在写数据的时候， 对于 ClientAbortException 之类的异常，
             * 是因为客户端取消了下载，而服务器端继续向浏览器写入数据时， 抛出这个异常，这个是正常的。
             * 尤其是对于迅雷这种吸血的客户端软件， 明明已经有一个线程在读取 bytes=1275856879-1275877358，
             * 如果短时间内没有读取完毕，迅雷会再启第二个、第三个。。。线程来读取相同的字节段， 直到有一个线程读取完毕，迅雷会 KILL
             * 掉其他正在下载同一字节段的线程， 强行中止字节读出，造成服务器抛 ClientAbortException。
             * 所以，我们忽略这种异常
             */
            // ignore
            log.info("客户端终止");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
    }
}
